//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package impl

import (
	"bytes"
	"fmt"
	"os/exec"
	"regexp"
	"strconv"
)

func Ping(addr string, pkgSize int32) (int32, error) {
	cmd := exec.Command("ping", "-c", "1", "-s", fmt.Sprint(pkgSize), addr)
	cmd.Env = []string{"LANG=C", "PATH=/bin:/sbin:/usr/bin:/usr/sbin"}
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return 0, err
	}
	err = cmd.Start()
	if err != nil {
		return 0, err
	}
	defer cmd.Wait()

	allBuf := []byte{}
	for {
		buf := make([]byte, 4096)
		n, err := stdout.Read(buf)
		if n > 0 {
			allBuf = append(allBuf, buf[:n]...)
		}
		if err != nil {
			break
		}
	}
	reader := bytes.NewBuffer(allBuf)
	reg, err := regexp.Compile(`.*bytes from.*time=([0-9\.]+)\s*ms`)
	if err != nil {
		return 0, err
	}
	for {
		line, err := reader.ReadString('\n')
		if err != nil {
			return 0, fmt.Errorf("no result")
		}
		matchs := reg.FindStringSubmatch(line)
		if len(matchs) > 1 {
			ttl, err := strconv.ParseFloat(matchs[1], 32)
			return int32(ttl), err
		}

	}
}
